package com.flyaudio.xiaopengautopilot.presenter;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

import androidx.annotation.NonNull;

import com.flyaudio.xiaopengautopilot.db.DBManager;
import com.flyaudio.xiaopengautopilot.entity.AvgConsumption;
import com.flyaudio.xiaopengautopilot.entity.Consumption;
import com.flyaudio.xiaopengautopilot.constant.JSONKeyName;
import com.flyaudio.xiaopengautopilot.entity.Sum;
import com.flyaudio.xiaopengautopilot.util.BroadCastUtil;
import com.flyaudio.xiaopengautopilot.util.ByteUtil;
import com.flyaudio.xiaopengautopilot.util.CalendarHandler;
import com.flyaudio.xiaopengautopilot.util.DataInfo;
import com.flyaudio.xiaopengautopilot.util.FileOpenPatch;
import com.flyaudio.xiaopengautopilot.util.FileTool;
import com.flyaudio.xiaopengautopilot.util.JSONUtil;
import com.flyaudio.xiaopengautopilot.util.L;
import com.flyaudio.xiaopengautopilot.constant.ModuleKey;
import com.flyaudio.xiaopengautopilot.constant.MsgViewUtil;
import com.github.mikephil.charting.data.BarEntry;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

public class IVehicleModule implements IModule {
    private final String TAG = "IVehicleModule";
    private VehicleModuleTest test;

    private IActivityCallback mCallback = null;


    private static IVehicleModule mModule = null;

    private Context mContext;
    private DBManager dbManager;
    private SimpleDateFormat simpleDateFormat;
    private DecimalFormat decimalFormat;

    //XiaoPeng轮胎规则 215/50 R17,齿轮比8.28
    private double DIAMETER_EU5 =  (215*0.55*2+17*25.4);   //轮胎直径
    private double PI_EU5 = 3.14;
    private double GEAR_RATIO_EU5 = 8.2579;                //齿轮比
    //DIAMETER_EU5*PI_EU5*Revolutions/GEAR_RATIO_EU5/1000) //计算里程
    private double distance = 0;

    private int mLight[] = {-1, -1, -1, -1,-1};
    private int mWindowLock[] = {-1, -1, -1, -1};
    private int mOuterMirror = -1 ,mTrunk = -1;
    private int mDoorLock[] = {-1, -1, -1, -1};
    private int mDrivingMode=-1, mEnergyMode = -1;
    private int mEnduranceMileage=-1;
    private int mSoc= -1;
    private int mSeatPosition[] = {-1,-1,-1,-1};
    private int mWindowPos[] = {-1,-1,-1,-1};
    private int mBackDoorState = -1;
    private int mDriverSeat_Wind_Warm_LV[] = {-1,-1};
    private int mWiperStatus[] = {-1,-1};
    private int mSafetyBelt[] = {-1,-1,-1};
    private int mWalkWarn[] = {-1,-1};

    public IVehicleModule(Context service) {
        L.d(TAG,"IVehicleModule  VehicleModuleTest");

        mModule = this;
//        test = new VehicleModuleTest(service);

        mContext = service;
        FileOpenPatch task  = new FileOpenPatch(new FileOpenPatch.TaskCallback() {
            @Override
            public void run() {
                initDbFile();
            }
        });
        initDbFile();
        JSONUtil.getInstance().init(service);
        dbManager = new DBManager(mContext, DBManager.DataBase_path);
        simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        decimalFormat = new DecimalFormat("0.0000");
    }
    private void initDbFile(){
        try {
            String dbPath =  mContext.getDatabasePath(DBManager.DataBase_path).getAbsolutePath();
            Log.d(TAG, "initDbFile: "+dbPath);
            try {
                if(FileTool.isExistFile(dbPath)){
                    FileTool.copyFileUsingFileChannels(dbPath,DBManager.DataBase_path_BACK);
                }else if(FileTool.isExistFile(DBManager.DataBase_path_BACK)){
                    FileTool.copyFileUsingFileChannels(DBManager.DataBase_path_BACK,dbPath);
                }

            } catch (IOException e) {
                e.printStackTrace();
            }
            String jsonPath =  mContext.getDatabasePath(JSONUtil.fileName).getAbsolutePath();
            Log.d(TAG, "initDbFile: "+jsonPath);
            try {
                String jsonBak = JSONUtil.fileDir+JSONUtil.fileName;
                if(FileTool.isExistFile(jsonPath)){
                    FileTool.copyFileUsingFileChannels(jsonPath,jsonBak);
                }else if(FileTool.isExistFile(jsonBak)){
                    FileTool.copyFileUsingFileChannels(jsonBak,jsonPath);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }catch (Exception e){

        }

    }
    public static synchronized IVehicleModule getInstance() {
        return mModule;
    }

    @Override
    public void dealData(byte[] buf) {
        L.v(TAG, "dealData " + ByteUtil.bytes2HexString(buf));

        //截取掉 controlID(4byte) controlType(1byte) extra(1byte)
        byte[] targets = new byte[buf.length - 6];
        System.arraycopy(buf, 6, targets, 0, buf.length - 6);

        int controlID = (int) (((buf[0]) & 0xff << 24) | ((buf[1] & 0xff) << 16) | ((buf[2] & 0xff << 8)) | (buf[3] & 0xff));
        senDealDataMsg(controlID,targets);
    }

    /**
     * dbc can数据
     *
     * @param targets
     */
    private void dbcCanData(byte[] targets) {
        switch (targets[0] & 0xff) {
            case 0x08: //标准帧
                StandardFrame(targets);
                break;
            case 0x88:  //扩展帧
                ExtendedFrame(targets);
                break;
        }
    }

    /**
     * mcu 扩展数据
     *
     * @param targets
     */
    void mcuExtendedData(byte[] targets) {
        switch (targets[0] & 0xff) {
            case 0x80:
                switch (targets[1] & 0xff) {
                    case 0x00: //每分钟功耗值 保留小数点4位
                        double powerConsumptVal = (((targets[2] & 0xff) << 24) | ((targets[3] & 0xff) << 16) | ((targets[4] & 0xff) << 8) | (targets[5] & 0xff)) * 0.0001;
                        Log.d(TAG, "mcuExtendedData: " + powerConsumptVal);
                        savePowerConsumption(decimalFormat.format(powerConsumptVal));
                        savePowerConsumptionSum(decimalFormat.format(powerConsumptVal));
                        if(!handler.hasMessages(Update_Mileage_View_delay)){
                            handler.sendEmptyMessageDelayed(Update_Mileage_View_delay, 5000);
                            handler.sendEmptyMessage(Update_Mileage_View);
                        }else{
                            handler.removeMessages(Update_Mileage_View);
                            handler.sendEmptyMessageDelayed(Update_Mileage_View,5000);
                        }
                        break;
                    case 0x01: //百公里耗油量/耗电量
                        int powerConsumptHundred = 0;
                        if((targets[2]&0x80) !=0){
                            powerConsumptHundred = 0xffff0000 +  ((targets[2] & 0xff) << 8) + (targets[3] & 0xff);
                        }else{
                            powerConsumptHundred = ((targets[2] & 0xff) << 8) + (targets[3] & 0xff);
                        }
                        Log.d(TAG, "powerConsumptHundred: " + powerConsumptHundred);
                        saveAvgPowerConsumption(powerConsumptHundred);
                        handler.sendEmptyMessage(Update_Mileage_View);
                        break;
                }
                break;
        }
    }

    public void senDealDataMsg(int what, Object arg) {
        Message msg = null;
        if (handler != null) {
            msg = handler.obtainMessage(what);
            msg.what = what;
            msg.obj = arg;
            handler.sendMessage(msg);
        } else {
            L.d(TAG, "mHandler is null");
        }
    }

    final int Update_Mileage_View = 1;
    final int Update_Mileage_View_delay = 2;
    final int Update_control_widget = 3;
    final int Update_control_widget_delay = 4;
    final int Update_Power_widget = 5;
    final int Update_Power_widget_delay = 6;
    final int Update_Endurance_widget = 7;
    final int Update_Endurance_widget_delay = 8;

    Handler handler = new Handler(){
        @Override
        public void handleMessage(@NonNull Message msg) {
            switch (msg.what){
                case 0x20ffff:
                    dbcCanData((byte[]) msg.obj);
                break;
                case 0x20fffe: //扩展MCU数据
                    mcuExtendedData((byte[]) msg.obj);
                 break;
                case Update_Mileage_View_delay:
                    if(hasMessages(Update_Mileage_View)){
                        removeMessages(Update_Mileage_View);
                        sendEmptyMessage(Update_Mileage_View);
                        sendEmptyMessageDelayed(Update_Mileage_View_delay, 5000);
                    }
                    break;
                case Update_Mileage_View:
                    SendActivityMessage(MsgViewUtil.Update_Mileage_View);
                    SendActivityMessage(MsgViewUtil.Update_KWh_AVG);
                    BroadCastUtil.senUpdateWidgetAction(mContext);
                    break;
                 case Update_control_widget_delay:
                    if(hasMessages(Update_control_widget)){
                        removeMessages(Update_control_widget);
                        sendEmptyMessage(Update_control_widget);
                        sendEmptyMessageDelayed(Update_control_widget_delay, 5000);
                    }
                    break;
                case Update_control_widget:
                    BroadCastUtil.senUpdateWidgetAction(mContext);
                    break;
                case Update_Power_widget_delay:
                    if(hasMessages(Update_Power_widget)){
                        removeMessages(Update_Power_widget);
                        sendEmptyMessage(Update_Power_widget);
                        sendEmptyMessageDelayed(Update_Power_widget_delay, 5000);
                    }
                    break;
                case Update_Power_widget:
                    BroadCastUtil.senUpdateWidgetAction(mContext);
                    break;
                case Update_Endurance_widget_delay:
                    if(hasMessages(Update_Endurance_widget)){
                        removeMessages(Update_Endurance_widget);
                        sendEmptyMessage(Update_Endurance_widget);
                        sendEmptyMessageDelayed(Update_Endurance_widget_delay, 5000);
                    }
                    break;
                case Update_Endurance_widget:
                    BroadCastUtil.senUpdateWidgetAction(mContext);
                    break;
            }
            super.handleMessage(msg);

        }
    };
    private void updateTotalMileageAvgData(String key,String powerConsumptVal,double mileage){
        try {
            JSONObject totalMap = new JSONObject(JSONUtil.getInstance().getMileageJSON(key,"{}").toString());
            if (totalMap.has(JSONKeyName.AcckWh)) {
                Double ConsumptVal = Double.parseDouble(powerConsumptVal) + totalMap.getDouble(JSONKeyName.AcckWh);
                totalMap.put(JSONKeyName.AcckWh,ConsumptVal);
            }else{
                totalMap.put(JSONKeyName.AcckWh,Double.parseDouble(powerConsumptVal));
            }
            if (totalMap.has(JSONKeyName.AccMileage)){
                Double mileageVal =  mileage + totalMap.getDouble(JSONKeyName.AccMileage);
                totalMap.put(JSONKeyName.AccMileage,mileageVal);
            }else{
                totalMap.put(JSONKeyName.AccMileage,mileage);
            }
            JSONUtil.getInstance().updateJson(key,totalMap);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    /**
     * 保存电耗值到数据库consumption表
     * @param powerConsumptVal
     */
    private void savePowerConsumption(String powerConsumptVal) {
        //获取总里程
        String sysTotalMileage = JSONUtil.getInstance().getMileageJSON(JSONKeyName.TotalMileage,"0").toString();

        //获取数据库最后一条记录
        HashMap<String, Object> map = dbManager.queryLastRecord();
        String sqlTotalMileage = (String) map.get("totalMileage");

        //一分钟耗电量所行驶里程 = 系统总里程 - 上一分钟数据库的总里程
        if(sqlTotalMileage==null || sqlTotalMileage.equals("")) {
            sqlTotalMileage = sysTotalMileage;
        }
        double mileage = Double.parseDouble(sysTotalMileage) - Double.parseDouble(sqlTotalMileage);
        Log.d(TAG,"savePowerConsumption  Date: " + simpleDateFormat.format(new Date())+"powerConsumptVal: " +  powerConsumptVal + " mileage: " +mileage  + " sysTotalMileage: " +Double.parseDouble(sysTotalMileage) + " sqlTotalMileage: " + sqlTotalMileage);

        Consumption consumption = new Consumption();

        consumption.setDate(simpleDateFormat.format(new Date()));
        consumption.setMileage(Double.toString(mileage));
        consumption.setTotalMileage(sysTotalMileage);
        consumption.setPowerConsumption(powerConsumptVal);
        dbManager.insert(consumption);
        updateTotalMileageAvgData(getMonthMileageAvgKeyName(),powerConsumptVal,mileage);
        updateTotalMileageAvgData(JSONKeyName.TotalMileageAvg,powerConsumptVal,mileage);
    }
    private String getMonthMileageAvgKeyName(){
        Date date = new Date();
        return JSONKeyName.MonthMileageAvg+"_"+(date.getMonth()+1);
    }

    /**
     * 保存耗电值累加到数据库sum表
     * @param powerConsumptVal
     */
    private void savePowerConsumptionSum(String powerConsumptVal) {
        //获取总里程
        String sysTotalMileage = JSONUtil.getInstance().getMileageJSON(JSONKeyName.TotalMileage,"0").toString();

        //查找数据库表中数据
        HashMap<String, Object> map = dbManager.querySumLastRecord();
        String sqlSumTotalMileage = (String) map.get("sumTotalMileage");

        //数据表无数据，默认值为0
        if(sqlSumTotalMileage==null || sqlSumTotalMileage.equals("")) {
            sqlSumTotalMileage = sysTotalMileage;
        }

        //一分钟内耗电量所行驶里程 = 系统总里程 - 上一分钟数据表的总里程
        double sunMileage = Double.parseDouble(sysTotalMileage) - Double.parseDouble(sqlSumTotalMileage);

        Date date=new Date(System.currentTimeMillis());
        String curSysDate=simpleDateFormat.format(date);

        //查找sum表中sumDate项
        Sum sum = dbManager.querySumDateItem(curSysDate);
        if(sum == null) { //插入数据
            sum = new Sum();
            sum.setSumDate(simpleDateFormat.format(new Date()));
            sum.setSumMileage(Double.toString(sunMileage));
            sum.setSumTotalMileage(sysTotalMileage);
            sum.setSumPowerConsumption(powerConsumptVal);
            dbManager.insert(sum);
        }else {  //修改数据
            double updateMileage = sunMileage + Double.parseDouble(sum.getSumMileage());
            double updatePowerConsumptionVal = Double.parseDouble(powerConsumptVal) + Double.parseDouble(sum.getSumPowerConsumption());
            sum.setSumDate(simpleDateFormat.format(new Date()));
            sum.setSumMileage(Double.toString(updateMileage));
            sum.setSumTotalMileage(sysTotalMileage);
            sum.setSumPowerConsumption(Double.toString(updatePowerConsumptionVal));
            dbManager.update(sum);
        }
    }
    private void saveAvgPowerConsumption(int powerConsumptVal) {

        String sysTotalMileage = JSONUtil.getInstance().getMileageJSON(JSONKeyName.TotalMileage,"0").toString();
        SimpleDateFormat DateFormat = new SimpleDateFormat("yyyy-MM-dd");
        AvgConsumption consumption = new AvgConsumption(sysTotalMileage,String.valueOf(powerConsumptVal),DateFormat.format(new Date()));
        L.d(TAG,"saveAvgPowerConsumption " + powerConsumptVal);
        if (powerConsumptVal!=0)
            dbManager.insert(consumption);
    }
    void StandardFrame(byte[] parame) {
        int functionID = (parame[1] << 8) | parame[2];
        byte[] targets = new byte[parame.length - 3];
        System.arraycopy(parame, 3, targets, 0, parame.length - 3);
        switch (functionID) {
            case 0x41:
                VCU_State_02(targets);
                break;
            case 0x50:
                BMS_TO_VCU1(targets);
                break;
            case 0x51:
                BMS_Status1(targets);
                break;
            case 0x53:
                BMS_ERROR(targets);
                break;
            case 0x60:
                BCM_State_01(targets);
                break;
            case 0x62:
                BCM_State_03(targets);
                break;
            case 0x70:
                MCU_State_01(targets);
                break;
            case 0x72:
                MCU_State_02(targets);
                break;

        }
    }

    private void VCU_State_02(byte[] targets) {
        Log.d(TAG,"VCU_State_02 " + ByteUtil.bytes2HexString(targets));
        double vcuCar_Speed = (((targets[5] & 0xff) << 8) + (targets[6] & 0xff)) * 0.01;
        DataInfo.getInstance().setDataParamerInfo(ModuleKey.VCU_Car_Speed, vcuCar_Speed);
    }

    private void ExtendedFrame(byte[] parame) {
        int functionID = (parame[1] << 24) | (parame[2] << 16) | (parame[3] << 8) | parame[4];
        byte[] targets = new byte[parame.length - 5];
        System.arraycopy(parame, 5, targets, 0, parame.length - 5);
        switch (functionID) {
            case 0x1d000001:
                break;
            case 0x1d000002:
                break;
            case 0x1d000003:
                break;
            case 0x1d000004:
                break;
            case 0x18ff33e9:
                break;
        }
    }

    private void MCU_State_01(byte[] paramer) {
        Log.d(TAG,"MCU_State_01 " + ByteUtil.bytes2HexString(paramer));
        int vcuDrivingMode = (paramer[3] & 0x18) >> 3;
        int vcuErvLevel = (paramer[3] & 0x60) >> 5;
        DataInfo.getInstance().setDataParamerInfo(ModuleKey.VCUDrivingMode, vcuDrivingMode);
        DataInfo.getInstance().setDataParamerInfo(ModuleKey.VCU_ERV_Level, vcuErvLevel);

        if (vcuDrivingMode != mDrivingMode) {
            SendActivityMessage(MsgViewUtil.Update_Driving_Mode);
            mDrivingMode = vcuDrivingMode;
        }

        if (vcuErvLevel != mEnergyMode) {
            SendActivityMessage(MsgViewUtil.Update_Energy_Mode);
            mEnergyMode = vcuErvLevel;
        }
    }

    public double computeMileage(int x){
        return (DIAMETER_EU5 * PI_EU5 * x / GEAR_RATIO_EU5 / 1000);
    }

    private void BMS_TO_VCU1(byte[] paramer) {
        Log.d(TAG,"BMS_TO_VCU1 " + ByteUtil.bytes2HexString(paramer));
       int HVState = (paramer[1]&0x1c)>>2; //上高压
       if(HVState == 2) {
           String totalMileageVal =  JSONUtil.getInstance().getMileageJSON(JSONKeyName.TotalMileage,"0").toString();
           JSONUtil.getInstance().updateJson(JSONKeyName.AutoRunMileage,totalMileageVal);
       }
    }

    private void MCU_State_02(byte[] paramer) {
        L.d(TAG, "MCU_State_02 " + ByteUtil.bytes2HexString(paramer));
        int dlccSpeed = paramer[4] & 0xff;   //定速巡航速度值
        DataInfo.getInstance().setDataParamerInfo(ModuleKey.DLCC_SPEED, dlccSpeed);

        int tempVal = ((paramer[0]& 0xff)<<24)|((paramer[1]& 0xff)<<16)|((paramer[2]& 0xff)<<8)|(paramer[3]& 0xff); //此次行驶里程
        double curDis = computeMileage(tempVal);
        Log.d(TAG,"MCU_State_02 " +" tempVal "+ tempVal + " curDis " + curDis);
        int totalDis = (int) curDis;
        JSONUtil.getInstance().updateJson(JSONKeyName.TotalMileage,String.valueOf(totalDis));
        //总里程为0时，上次充电后的行驶里程需要置0操作
        if(totalDis == 0) {
            JSONUtil.getInstance().updateJson(JSONKeyName.LastChargeMileage,0);
        }
//        distance = curDis;
        Log.d(TAG,"MCU_State_02 " +" tempVal "+ tempVal + " curDis " + curDis + " distance " +distance);
//        if (curDis > distance) {
//            int revolutions = (int) (curDis - distance + Integer.parseInt(JSONUtil.getInstance().getMileageJSON(JSONKeyName.TotalMileage, "0").toString()));
//            Log.d(TAG, "MCU_State_02: " + revolutions + " curDis " + curDis + " distance " + distance + " tempVal " + tempVal);
//            JSONUtil.getInstance().updateJson(JSONKeyName.TotalMileage,String.valueOf(revolutions));
//            distance = curDis;
//        }
        SendActivityMessage(MsgViewUtil.Update_Condition_Dialog);

    }

    private void BCM_State_01(byte[] paramer) {
        L.d(TAG, "BCM_State_01 " + ByteUtil.bytes2HexString(paramer));
        //1---6
        int highBeamLight_Status = paramer[0] & 0x01;
        int lowBeamLight_Status = (paramer[0] & 0x02) >> 1;
        int frontFogLight_Status = (paramer[0] & 0x04) >> 2;
        int frontTailLight_Status = (paramer[0] & 0x08) >> 3;
        int drivingLight_Status = (paramer[0] & 0x10) >> 4;
        int goHomeModeLight_Status = (paramer[0] & 0x20) >> 5;
        int leftTurnLight_Status = (paramer[0] & 0x40) >> 6;
        int rightTurnLight_Status = (paramer[0] & 0x80) >> 7;
        DataInfo.getInstance().setDataParamerInfo(ModuleKey.BCM_HighBeamLight_Status, highBeamLight_Status);

        DataInfo.getInstance().setDataParamerInfo(ModuleKey.BCM_LowBeamLight_Status, lowBeamLight_Status);
        DataInfo.getInstance().setDataParamerInfo(ModuleKey.BCM_FrontFogLight_Status, frontFogLight_Status);
        DataInfo.getInstance().setDataParamerInfo(ModuleKey.BCM_FrontTailLight_Status, frontTailLight_Status);
        DataInfo.getInstance().setDataParamerInfo(ModuleKey.BCM_DrivingLight_Status, drivingLight_Status);
        DataInfo.getInstance().setDataParamerInfo(ModuleKey.BCM_GoHomeModeLight_Status, goHomeModeLight_Status);
        DataInfo.getInstance().setDataParamerInfo(ModuleKey.BCM_LeftTurnLight_Status, leftTurnLight_Status);
        DataInfo.getInstance().setDataParamerInfo(ModuleKey.BCM_RightTurnLight_Status, rightTurnLight_Status);

        //7---13
        int frontWiperHigh_Status = paramer[1] & 0x01;
        int frontWiperLow_Status = (paramer[1] & 0x02) >> 1;
        int frontWiperIntt_Status = (paramer[1] & 0x04) >> 2;
        int frontWiperGear_Status = (paramer[1] & 0x18) >> 3;
        int frontWash_Status = (paramer[1] & 0x20) >> 4;
        int frontWiperReset_Status = (paramer[1] & 0x40) >> 5;
        int frontCover_Status = (paramer[1] & 0x80) >> 6;

        DataInfo.getInstance().setDataParamerInfo(ModuleKey.BCM_FrontWiperHigh_Status, frontWiperHigh_Status);
        DataInfo.getInstance().setDataParamerInfo(ModuleKey.BCM_FrontWiperLow_Status, frontWiperLow_Status);
        DataInfo.getInstance().setDataParamerInfo(ModuleKey.BCM_FrontWiperInt_Status, frontWiperIntt_Status);
        DataInfo.getInstance().setDataParamerInfo(ModuleKey.BCM_FrontWiperGear_Status, frontWiperGear_Status);
        DataInfo.getInstance().setDataParamerInfo(ModuleKey.BCM_FrontWashStatus, frontWash_Status);
        DataInfo.getInstance().setDataParamerInfo(ModuleKey.BCM_FrontWiperReset_Status, frontWiperReset_Status);
        DataInfo.getInstance().setDataParamerInfo(ModuleKey.BCM_FrontCover_Status, frontCover_Status);

        //14--20
        int backCarLight_Status = (paramer[2] & 0x01);
        int brakeCarLight_Status = (paramer[2] & 0x02) >> 1;
        int rearFogLight_Status = (paramer[2] & 0x04) >> 2;
        int rearTailLight_Status = (paramer[2] & 0x08) >> 3;
        int rearWiper_Status = (paramer[2] & 0x10) >> 4;
        int rearWash_Status = (paramer[2] & 0x20) >> 5;
        int rearTrunk_Status = (paramer[2] & 0x40) >> 6;
        DataInfo.getInstance().setDataParamerInfo(ModuleKey.BCM_BackCarLight_Status, backCarLight_Status);
        DataInfo.getInstance().setDataParamerInfo(ModuleKey.BCM_BrakeCarLight_Status, brakeCarLight_Status);
        DataInfo.getInstance().setDataParamerInfo(ModuleKey.BCM_RearFogLight_Status, rearFogLight_Status);
        DataInfo.getInstance().setDataParamerInfo(ModuleKey.BCM_RearTailLight_Status, rearTailLight_Status);
        DataInfo.getInstance().setDataParamerInfo(ModuleKey.BCM_RearWiper_Status, rearWiper_Status);
        DataInfo.getInstance().setDataParamerInfo(ModuleKey.BCM_RearWash_Status, rearWash_Status);
        DataInfo.getInstance().setDataParamerInfo(ModuleKey.BCM_RearTrunk_Status, rearTrunk_Status);

        //21--24
        int driverWindow_Status = (paramer[3] & 0x03);
        int passengerWindow_Status = (paramer[3] & 0x0c) >> 2;
        int rearLeftWindow_Status = (paramer[3] & 0x30) >> 4;
        int rearRightWindow_Status = (paramer[3] & 0xc0) >> 6;
        DataInfo.getInstance().setDataParamerInfo(ModuleKey.BCM_DriverWindow_Status, driverWindow_Status);
        DataInfo.getInstance().setDataParamerInfo(ModuleKey.BCM_PassengerWindow_Status, passengerWindow_Status);
        DataInfo.getInstance().setDataParamerInfo(ModuleKey.BCM_RearLeftWindow_Status, rearLeftWindow_Status);
        DataInfo.getInstance().setDataParamerInfo(ModuleKey.BCM_RearRightWindow_Status, rearRightWindow_Status);


        //25--30
        int driverSideLock_Status = (paramer[4] & 0x01);
        int passengerSideLock_Status = (paramer[4] & 0x02) >> 1;
        int leftRearLock_Status = (paramer[4] & 0x04) >> 2;
        int rightRearLock_Status = (paramer[4] & 0x08) >> 3;
        int outerMirror_Status = (paramer[4] & 0x30) >> 4;
        DataInfo.getInstance().setDataParamerInfo(ModuleKey.BCM_DriverSideLock_Status, driverSideLock_Status);
        DataInfo.getInstance().setDataParamerInfo(ModuleKey.BCM_PassengerSideLock_Status, passengerSideLock_Status);
        DataInfo.getInstance().setDataParamerInfo(ModuleKey.BCM_LeftRearLock_Status, leftRearLock_Status);
        DataInfo.getInstance().setDataParamerInfo(ModuleKey.BCM_RightRearLock_Status, rightRearLock_Status);
        DataInfo.getInstance().setDataParamerInfo(ModuleKey.BCM_OuterMirror_Status, outerMirror_Status);

        //31--37
        int driverDoor_Status = (paramer[5] & 0x01);
        int passengerDoor_Status = (paramer[5] & 0x02) >> 1;
        int rearLeftDoor_Status = (paramer[5] & 0x04) >> 2;
        int rearRightDoor_Status = (paramer[5] & 0x08) >> 3;
        int driverSafetyBelt = (paramer[5] & 0x20) >> 5;
        int passengerSafetyBelt = (paramer[5] & 0x40) >> 6;
        int rearMidSafetyBelt = (paramer[5] & 0x80) >> 7;

        DataInfo.getInstance().setDataParamerInfo(ModuleKey.BCM_DriverDoor_Status, driverDoor_Status);
        DataInfo.getInstance().setDataParamerInfo(ModuleKey.BCM_PassengerDoor_Status, passengerDoor_Status);
        DataInfo.getInstance().setDataParamerInfo(ModuleKey.BCM_RearLeftDoor_Status, rearLeftDoor_Status);
        DataInfo.getInstance().setDataParamerInfo(ModuleKey.BCM_RearRightDoor_Status, rearRightDoor_Status);
        DataInfo.getInstance().setDataParamerInfo(ModuleKey.BCM_DriverSafetyBelt, driverSafetyBelt);
        DataInfo.getInstance().setDataParamerInfo(ModuleKey.BCM_PassengerSafetyBelt, passengerSafetyBelt);
        DataInfo.getInstance().setDataParamerInfo(ModuleKey.BCM_REARMIDSAFETYBELT, rearMidSafetyBelt);

        //38--
        int rearLeftSafetyBelt = (paramer[6] & 0x01);
        int rearRightSafetyBelt = (paramer[6] & 0x02) >> 1;
        int walkWarnSw_Status = (paramer[6] & 0x04) >> 2;
        int walkWarnVoice_Status = (paramer[6] & 0x08) >> 3;
        int driverSeat_WindLV = (paramer[6] & 0x30) >>4;
        int driverSeat_WarnLV = (paramer[6] & 0xc0) >> 6;

        DataInfo.getInstance().setDataParamerInfo(ModuleKey.BCM_REARLEFTSAFETYBELT, rearLeftSafetyBelt);
        DataInfo.getInstance().setDataParamerInfo(ModuleKey.BCM_REARRIGHTSAFETYBELT, rearRightSafetyBelt);
        DataInfo.getInstance().setDataParamerInfo(ModuleKey.BCM_WALKWARNSW_STATUS, walkWarnSw_Status);
        DataInfo.getInstance().setDataParamerInfo(ModuleKey.BCM_WALKWARNVOICE_STATUS, walkWarnVoice_Status);
        DataInfo.getInstance().setDataParamerInfo(ModuleKey.BCM_DRIVERSEAT_WINDLV, driverSeat_WindLV);
        DataInfo.getInstance().setDataParamerInfo(ModuleKey.BCM_DRIVERSEAT_WARNLV, driverSeat_WarnLV);

        if (lowBeamLight_Status != mLight[0] || frontTailLight_Status != mLight[1] ||
                rearFogLight_Status != mLight[2] || rearTailLight_Status != mLight[3] ||
                highBeamLight_Status != mLight[4]) {
            JSONUtil.getInstance().updateJson(JSONKeyName.LowBeanLight,lowBeamLight_Status);
            JSONUtil.getInstance().updateJson(JSONKeyName.FrontTailLight,frontTailLight_Status);
            JSONUtil.getInstance().updateJson(JSONKeyName.RearFogLight,rearFogLight_Status);
            JSONUtil.getInstance().updateJson(JSONKeyName.RearTailLight,rearTailLight_Status);
            JSONUtil.getInstance().updateJson(JSONKeyName.HighBeanLight,highBeamLight_Status);
            SendActivityMessage(MsgViewUtil.Update_Light_State);
            mLight[0] = lowBeamLight_Status;
            mLight[1] = frontTailLight_Status;
            mLight[2] = rearFogLight_Status;
            mLight[3] = rearTailLight_Status;
            mLight[4] = highBeamLight_Status;
        }

        if (driverSideLock_Status != mDoorLock[0] || passengerSideLock_Status != mDoorLock[1] ||
                leftRearLock_Status != mDoorLock[2] || rightRearLock_Status != mDoorLock[3]) {
            JSONUtil.getInstance().updateJson(JSONKeyName.DoorLockLF,driverSideLock_Status);
            JSONUtil.getInstance().updateJson(JSONKeyName.DoorLockRF,passengerSideLock_Status);
            JSONUtil.getInstance().updateJson(JSONKeyName.DoorLockLR,leftRearLock_Status);
            JSONUtil.getInstance().updateJson(JSONKeyName.DoorLockRR,rightRearLock_Status);
            SendActivityMessage(MsgViewUtil.Update_DoorLock_State);
            if(!handler.hasMessages(Update_control_widget_delay)){
                handler.sendEmptyMessageDelayed(Update_control_widget_delay, 5000);
                handler.sendEmptyMessage(Update_control_widget);
            }else{
                handler.removeMessages(Update_control_widget);
                handler.sendEmptyMessageDelayed(Update_control_widget,5000);
            }

            mDoorLock[0] = driverSideLock_Status;
            mDoorLock[1] = passengerSideLock_Status;
            mDoorLock[2] = leftRearLock_Status;
            mDoorLock[3] = rightRearLock_Status;
        }

//        if (driverWindow_Status != mWindowLock[0] || passengerWindow_Status != mWindowLock[1] ||
//                rearLeftWindow_Status != mWindowLock[2] || rearRightWindow_Status != mWindowLock[3]) {
//            SendActivityMessage(MsgViewUtil.Update_WindowLock_State);
//            mWindowLock[0] = driverWindow_Status;
//            mWindowLock[1] = passengerWindow_Status;
//            mWindowLock[2] = rearLeftWindow_Status;
//            mWindowLock[3] = rearRightWindow_Status;
//        }

//        if (rearTrunk_Status != mTrunk) {
//            SendActivityMessage(MsgViewUtil.Update_Trunk_State);
//            mTrunk = rearTrunk_Status;
//        }

        if (outerMirror_Status != mOuterMirror) {
            JSONUtil.getInstance().updateJson(JSONKeyName.OuterMirrorState,outerMirror_Status);
            SendActivityMessage(MsgViewUtil.Update_OuterMirror_State);
            mOuterMirror = outerMirror_Status;
        }

        if((driverSeat_WindLV != mDriverSeat_Wind_Warm_LV[0]) || (driverSeat_WarnLV != mDriverSeat_Wind_Warm_LV[1])) {
            SendActivityMessage(MsgViewUtil.UpateDriverSeatWindWarmLv);
            JSONUtil.getInstance().updateJson(JSONKeyName.DriverSeatWindLV,driverSeat_WindLV);
            JSONUtil.getInstance().updateJson(JSONKeyName.DriverSeatWarm_LV,driverSeat_WarnLV);
            mDriverSeat_Wind_Warm_LV[0] = driverSeat_WindLV;
            mDriverSeat_Wind_Warm_LV[1] = driverSeat_WarnLV;
        }

        if((frontWiperGear_Status != mWiperStatus[0]) || (rearWiper_Status != mWiperStatus[1])) {
            SendActivityMessage(MsgViewUtil.UpdateWiperStatus);
            JSONUtil.getInstance().updateJson(JSONKeyName.FontWiperGear,frontWiperGear_Status);
            JSONUtil.getInstance().updateJson(JSONKeyName.RearWiper,rearWiper_Status);
            mWiperStatus[0] = frontWiperGear_Status;
            mWiperStatus[1] = rearWiper_Status;
        }

        if((rearMidSafetyBelt != mSafetyBelt[0] ) || (rearLeftSafetyBelt != mSafetyBelt[1]) || (rearRightSafetyBelt != mSafetyBelt[2])) {
            SendActivityMessage(MsgViewUtil.UpdateSafetyBelt);
            JSONUtil.getInstance().updateJson(JSONKeyName.RearMidSafetyBelt,rearMidSafetyBelt);
            JSONUtil.getInstance().updateJson(JSONKeyName.RearLeftSafetyBelt,rearLeftSafetyBelt);
            JSONUtil.getInstance().updateJson(JSONKeyName.RearRightSafetyBelt,rearRightSafetyBelt);

            mSafetyBelt[0] = rearMidSafetyBelt;
            mSafetyBelt[1] = rearLeftSafetyBelt;
            mSafetyBelt[2] = rearRightSafetyBelt;
        }

        if((walkWarnSw_Status != mWalkWarn[0]) || walkWarnVoice_Status != mWalkWarn[1]) {
            SendActivityMessage(MsgViewUtil.UpdateWalkWarn);
            JSONUtil.getInstance().updateJson(JSONKeyName.WalkWarnSw,walkWarnSw_Status);
            JSONUtil.getInstance().updateJson(JSONKeyName.WalkWarnVoice,walkWarnVoice_Status);
            mWalkWarn[0] = walkWarnSw_Status;
            mWalkWarn[1] = walkWarnVoice_Status;
        }
    }

    private void BCM_State_03(byte[] paramer) {
        L.d(TAG, "BCM_State_03 " + ByteUtil.bytes2HexString(paramer));
        int seatMoveDirect = paramer[0]&0x0f;
        int seatFRPosition = paramer[1]&0xff;
        int seatUDPosition = paramer[2]&0xff;
        int seatBackPositon = paramer[3]&0xff;

        int lfWindowPos =  paramer[5]&0x0f;
        int rfWindowPos = (paramer[5]&0xf0)>>4;
        int lrWindowPos = paramer[6]&0x0f;
        int rrWindowPos = (paramer[6]&0xf0)>>4;

        int backDoorState = (paramer[0]&0x30)>>4;

        DataInfo.getInstance().setDataParamerInfo(ModuleKey.BCM_DRIVERSEAT_MOVEDIRECT, seatMoveDirect);
        DataInfo.getInstance().setDataParamerInfo(ModuleKey.BCM_DRIVERSEAT_FR_POSITION,seatFRPosition);
        DataInfo.getInstance().setDataParamerInfo(ModuleKey.BCM_DRIVERSEAT_UD_POSITION,seatUDPosition);
        DataInfo.getInstance().setDataParamerInfo(ModuleKey.BCM_DRIVERSEAT_BACKREST_POSITION,seatBackPositon);

        DataInfo.getInstance().setDataParamerInfo(ModuleKey.BCM_DRIVERWINDOWPOS, lfWindowPos);
        DataInfo.getInstance().setDataParamerInfo(ModuleKey.BCM_PASSENGERWINDOWPOS, rfWindowPos);
        DataInfo.getInstance().setDataParamerInfo(ModuleKey.BCM_REARLEFTWINDOWPOS, lrWindowPos);
        DataInfo.getInstance().setDataParamerInfo(ModuleKey.BCM_REARRIGHTWINDOWPOS, rrWindowPos);

        DataInfo.getInstance().setDataParamerInfo(ModuleKey.BCM_BACKDOORSTATE, backDoorState);

        if(seatMoveDirect != mSeatPosition[0] || seatFRPosition != mSeatPosition[1] ||
                seatUDPosition != mSeatPosition[2] || seatBackPositon != mSeatPosition[3]) {
            JSONUtil.getInstance().updateJson(JSONKeyName.SeatMoveDirect,seatMoveDirect);
            JSONUtil.getInstance().updateJson(JSONKeyName.SeatFRPos,seatFRPosition);
            JSONUtil.getInstance().updateJson(JSONKeyName.SeatUDPos,seatUDPosition);
            JSONUtil.getInstance().updateJson(JSONKeyName.SeatBackPos,seatBackPositon);
            SendActivityMessage(MsgViewUtil.Update_Seat_View);

            mSeatPosition[0] =  seatMoveDirect;
            mSeatPosition[1] =  seatFRPosition;
            mSeatPosition[2] =  seatUDPosition;
            mSeatPosition[3] =  seatBackPositon;
        }

        if(lfWindowPos != mWindowPos[0] || rfWindowPos != mWindowPos[1] ||
                lrWindowPos != mWindowPos[2] || rrWindowPos != mWindowPos[3]) {
            JSONUtil.getInstance().updateJson(JSONKeyName.WindowPosLF,lfWindowPos);
            JSONUtil.getInstance().updateJson(JSONKeyName.WindowPosRF,rfWindowPos);
            JSONUtil.getInstance().updateJson(JSONKeyName.WindowPosLR,lrWindowPos);
            JSONUtil.getInstance().updateJson(JSONKeyName.WindowPosRR,rrWindowPos);
            SendActivityMessage(MsgViewUtil.Update_Window_View);

            mWindowPos[0] = lfWindowPos;
            mWindowPos[1] = rfWindowPos;
            mWindowPos[2] = lrWindowPos;
            mWindowPos[3] = rrWindowPos;
        }
        if(backDoorState != mBackDoorState) {
            JSONUtil.getInstance().updateJson(JSONKeyName.BackDoorState,backDoorState);
            SendActivityMessage(MsgViewUtil.Update_Trunk_State);
            mBackDoorState = backDoorState;
        }

    }

    private void BMS_Status1(byte[] parame) {
        int BMS_SOC = (parame[1] & 0xff); //soc值
        DataInfo.getInstance().setDataParamerInfo(ModuleKey.BMS_SOC, BMS_SOC);
        if (BMS_SOC != mSoc) {
            JSONUtil.getInstance().updateJson(JSONKeyName.BmsSoc, BMS_SOC);
            SendActivityMessage(MsgViewUtil.Update_Soc);
            if(!handler.hasMessages(Update_Power_widget_delay)){
                handler.sendEmptyMessageDelayed(Update_Power_widget_delay, 5000);
                handler.sendEmptyMessage(Update_Power_widget);
            }else{
                handler.removeMessages(Update_Power_widget);
                handler.sendEmptyMessageDelayed(Update_Power_widget,5000);
            }
//            BroadCastUtil.senUpdateWidgetAction(mContext);
            mSoc = BMS_SOC;
        }
    }

    private void BMS_ERROR(byte[] parame) {
        L.d(TAG, "BMS_ERROR " + ByteUtil.bytes2HexString(parame));
        int fastCharge = (parame[2]&0x10)>>4; //快充
        int slowCharge = (parame[2] & 0x20) >> 5; //慢充
        int enduranceMileage =((parame[5]&0x0f)<<8)|(parame[6]&0xff); //续航里程

        DataInfo.getInstance().setDataParamerInfo(ModuleKey.BMS_EnduranceMileage, enduranceMileage);
        if (enduranceMileage != mEnduranceMileage) {
            JSONUtil.getInstance().updateJson(JSONKeyName.EnduranceMileage, enduranceMileage);
            SendActivityMessage(MsgViewUtil.Update_Endurance_Mileage);

            if(!handler.hasMessages(Update_Endurance_widget_delay)){
                handler.sendEmptyMessageDelayed(Update_Endurance_widget_delay, 5000);
                handler.sendEmptyMessage(Update_Endurance_widget);
            }else{
                handler.removeMessages(Update_Endurance_widget);
                handler.sendEmptyMessageDelayed(Update_Endurance_widget,5000);
            }
            //BroadCastUtil.senUpdateWidgetAction(mContext);
            mEnduranceMileage = enduranceMileage;
        }

        if(fastCharge == 1 || slowCharge == 1 ) {
            String totalMileageVal =  JSONUtil.getInstance().getMileageJSON(JSONKeyName.TotalMileage,"0").toString();
            JSONUtil.getInstance().updateJson(JSONKeyName.LastChargeMileage,totalMileageVal);
        }

    }

    private void TPMSMessage(byte[] parame) {
        double vehicle_tpms_lf=0.0;
        double  vehicle_tpms_rf=0.0;
        double  vehicle_tpms_lr=0.0;
        double vehicle_tpms_rr=0.0;

        double  doublevehicle_tpms_temp_lf=0.0;
        double vehicle_tpms_temp_rf= 0.0;
        double vehicle_tpms_temp_lr= 0.0;
        double vehicle_tpms_temp_rr= 0.0;

        DataInfo.getInstance().setDataParamerInfo(ModuleKey.TPMS_VEHICLE_TPMS_LF, vehicle_tpms_lf);
        DataInfo.getInstance().setDataParamerInfo(ModuleKey.TPMS_VEHICLE_TPMS_RF, vehicle_tpms_rf);
        DataInfo.getInstance().setDataParamerInfo(ModuleKey.TPMS_VEHICLE_TPMS_LR, vehicle_tpms_lr);
        DataInfo.getInstance().setDataParamerInfo(ModuleKey.TPMS_VEHICLE_TPMS_RR, vehicle_tpms_rr);

        DataInfo.getInstance().setDataParamerInfo(ModuleKey.TPMS_DOUBLEVEHICLE_TPMS_TEMP_LF, doublevehicle_tpms_temp_lf);
        DataInfo.getInstance().setDataParamerInfo(ModuleKey.TPMS_VEHICLE_TPMS_TEMP_RF, vehicle_tpms_temp_rf);
        DataInfo.getInstance().setDataParamerInfo(ModuleKey.TPMS_VEHICLE_TPMS_TEMP_LR, vehicle_tpms_temp_lr);
        DataInfo.getInstance().setDataParamerInfo(ModuleKey.VTPMS_EHICLE_TPMS_TEMP_RR, vehicle_tpms_temp_rr);
    }

   public void setCallBack(IActivityCallback callBack) {
        this.mCallback = callBack;
    }

    public void SendActivityMessage(int message) {
        if (mCallback != null)
            mCallback.sendMsg(message, null);
    }

    private String firstDate = "";
    private String lastDate = "";

    public String computeFirstDate(){
        firstDate = dbManager.querySumDateMin();
        lastDate = dbManager.querySumDateMax();
        if(firstDate == null|| lastDate == null){
            firstDate = lastDate = simpleDateFormat.format(new Date());
        }
        CalendarHandler calendarHandler = new CalendarHandler();
        int dates = (int)calendarHandler.dateDiff(firstDate,lastDate);
        if (dates > CalendarHandler.MAX_DATES){
            calendarHandler.init(firstDate);
            firstDate = calendarHandler.toString(calendarHandler.startDateToNDay(dates+1 - CalendarHandler.MAX_DATES));
            dbManager.deleteSumByDateBefore(firstDate);
        }
        L.d(TAG,"firstDate "+ firstDate + " lastDate " + lastDate);
        return firstDate;
    }
    public List<BarEntry> getPowerConsumptionInDate(){
       // dbManager.querySumDateItem();
        List<Sum> list = dbManager.querySumInDate(firstDate,lastDate);
        ArrayList<BarEntry> listEntry = new ArrayList<>();
        Calendar st=Calendar.getInstance();
        Calendar ed=Calendar.getInstance();
        try {
            st.setTime(simpleDateFormat.parse(firstDate));
            ed.setTime(simpleDateFormat.parse(lastDate));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        int i = 0;
        int j = 0;
        while(!st.after(ed)){
            String date = simpleDateFormat.format(st.getTime());
            st.add(Calendar.DAY_OF_YEAR,1);
            if (list.size() > i &&date.equals(list.get(i).getSumDate())) {
                listEntry.add(new BarEntry(j++,Float.parseFloat(list.get(i).getSumPowerConsumption())));
                ++i;
            }else{
                listEntry.add(new BarEntry(j++,0));
            }
        }
        if(listEntry.size() < 35){
            for (i = listEntry.size(); i < 35; ++i){
                listEntry.add(new BarEntry(i,0));
            }
        }

        L.d(TAG,"listEntry size " + listEntry.size());
        return listEntry;
    }
    public ArrayList<BarEntry> getPowerConsumptionInMonth(){

        Calendar st=Calendar.getInstance();
        Calendar ed=Calendar.getInstance();

        try {
            Date first = simpleDateFormat.parse(firstDate);
            Date last = simpleDateFormat.parse(lastDate);
            first.setDate(1);
            st.setTime(first);
            ed.setTime(last);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        String indexFirst = firstDate;
        String indexLast;
        ArrayList<BarEntry> listEntry = new ArrayList<>();
        int j = 0;
        while(!st.after(ed)){
            indexLast = simpleDateFormat.format(st.getTime());
            st.add(Calendar.MONTH,1);
            float power = dbManager.queryPowerConsumptionInDate(indexFirst,indexLast);
            listEntry.add(new BarEntry(j++,power));
            indexFirst = indexLast;
        }

        L.d(TAG,"listEntry size " + listEntry.size());
        return listEntry;
    }
    public ArrayList<BarEntry> getMileageData(int max,int setp){
        String temp = JSONUtil.getInstance().getMileageJSON(JSONKeyName.TotalMileage,"0").toString();
        int sysTotalMileage = Integer.parseInt(temp);
        int setpMile = setp* 1000;
        int indexBegin = max*1000 + setpMile;
        int indexEnd = 0;
        ArrayList<BarEntry> listEntry = new ArrayList<>();
        for (int i = -max;i <= 0;i+=setp){
            indexEnd = indexBegin - setpMile;
            HashMap<String,Object> map = dbManager.queryAvgPowerSumInMileageRange(sysTotalMileage - indexBegin,sysTotalMileage - indexEnd);

            float power = Float.parseFloat(map.get("power").toString());
            if(power > 80)
                power = 80;
            if(power < -20)
                power = -20;
            listEntry.add(new BarEntry(i, power+20));

            indexBegin = indexEnd;
        }

        return listEntry;
    }

    public float getTotalPowerAvg(){

//        try {
//
////            JSONObject totalMap = new JSONObject(JSONUtil.getInstance().getMileageJSON(JSONKeyName.TotalMileageAvg,"{}").toString());
////            if (totalMap.has(JSONKeyName.AcckWh)&&totalMap.has(JSONKeyName.AccMileage)) {
////                double AcckWh =  totalMap.getDouble(JSONKeyName.AcckWh);
////                double AccMileage = totalMap.getDouble(JSONKeyName.AccMileage);
////                if(AccMileage!=0)
////                    return (float) (AcckWh * 100 * 1000 / AccMileage);
////                else
////                    return 0;
////            }
//
//        } catch (JSONException e) {
//            e.printStackTrace();
//        }
        HashMap<String,Object> map = dbManager.queryAVGInTotal();
        float power = Float.parseFloat(map.get("power").toString());
        return power;
//        return 0;
    }
    public float getMonthPowerAvg(){

//        try {
//
//            JSONObject totalMap = new JSONObject(JSONUtil.getInstance().getMileageJSON(getMonthMileageAvgKeyName(),"{}").toString());
//
//            if (totalMap.has(JSONKeyName.AcckWh)&&totalMap.has(JSONKeyName.AccMileage)) {
//                double AcckWh = (Double) totalMap.getDouble(JSONKeyName.AcckWh);
//                double AccMileage = (Double) totalMap.getDouble(JSONKeyName.AccMileage);
//
//                if(AccMileage != 0)
//                    return (float) (AcckWh * 100 * 1000 / AccMileage);
//                else
//                    return 0;
//            }
//
//        } catch (JSONException e) {
//            e.printStackTrace();
//        }
//        return 0;

        Calendar st=Calendar.getInstance();
        Calendar ed=Calendar.getInstance();
        ed.add(Calendar.DAY_OF_MONTH,1);
        st.set(Calendar.DAY_OF_MONTH,1);
        st.set(Calendar.AM_PM,0);
        st.set(Calendar.HOUR,0);
        st.set(Calendar.MINUTE,0);
        st.set(Calendar.SECOND,0);
        SimpleDateFormat DateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String begin = DateFormat.format(st.getTime());
        String end = DateFormat.format(ed.getTime());
        Log.d(TAG, "getMonthPowerAvg: " + begin + " end " + end);
        HashMap<String,Object> map = dbManager.queryAVGInMonth(begin,end);
        float power = Float.parseFloat(map.get("power").toString());
        return power;
    }

    public double getMileageData(int val){
        String temp =JSONUtil.getInstance().getMileageJSON(JSONKeyName.TotalMileage,"0").toString();
        int sysTotalMileage = Integer.parseInt(temp);
        Log.d(TAG,"getMileageData  sysTotalMileage: " +sysTotalMileage);
        HashMap<String,Object> map = dbManager.queryAvgPowerSumInMileageRange(sysTotalMileage - val,sysTotalMileage - 0);

        float power = Float.parseFloat(map.get("power").toString());
        Log.d(TAG,"getMileageData  : "  + " power: " +power);
        if(power > 80)
            power = 80;
        if(power < -20)
            power = -20;
        return  power+20;
    }

    public void resetKWhAvg() {
        JSONUtil.getInstance().updateJson(getMonthMileageAvgKeyName(),"{}");
        JSONUtil.getInstance().updateJson(JSONKeyName.TotalMileageAvg,"{}");
        SendActivityMessage(MsgViewUtil.Update_KWh_AVG);
    }

}
